package com.concerneyes.pay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.concerneyes.CEApp;
import com.concerneyes.R;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import http.HttpAsyncTask;
import http.JsonMap;
import http.Url;
import util.ActivityUtil;

/**
 * 支付宝、微信支付
 */
public class DialogPay {
    private static final int SDK_PAY_FLAG = 1;
    private Context context;
    private boolean isWeChat = true;
    private PaySuccessListener payListener;

    /**
     * 支付dialog
     *
     * @param context
     * @param ordNum  订单号
     */
    public DialogPay(Context context, String ordNum, PaySuccessListener payListener) {
        this.context = context;
        this.payListener = payListener;
        if (!TextUtils.isEmpty(ordNum)) {
            showPayDialog(context, ordNum);
        } else {
//			ToastHelper.getInstance(context, R.string.network_error_tip);
        }

    }

    @SuppressLint("NewApi")
    private void showPayDialog(final Context context, final String ordNum) {

        final Dialog dialog = new Dialog(context, R.style.Theme_Dialog_Translucent);
        dialog.setCanceledOnTouchOutside(true);
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_pay, null);
        dialog.setContentView(view);
        dialog.show();
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        int width = context.getResources().getDisplayMetrics().widthPixels;
        lp.width = 5 * width / 6;
        lp.gravity = Gravity.CENTER;
        dialogWindow.setAttributes(lp);
        RelativeLayout rl_wechat = (RelativeLayout) view.findViewById(R.id.rl_wechat);
        RelativeLayout rl_alipay = (RelativeLayout) view.findViewById(R.id.rl_alipay);
        final ImageView iv_alipay = (ImageView) view.findViewById(R.id.iv_alipay);
        final ImageView iv_wechat = (ImageView) view.findViewById(R.id.iv_wechat);
        final TextView tv_pay = (TextView) view.findViewById(R.id.tv_pay);
        final ImageView pay_cancel = (ImageView) view.findViewById(R.id.pay_cancel);

        rl_wechat.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_alipay.setImageResource(R.drawable.btn_unselected);
                iv_wechat.setImageResource(R.drawable.btn_selected);
                isWeChat = true;
            }
        });
        rl_alipay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_alipay.setImageResource(R.drawable.btn_selected);
                iv_wechat.setImageResource(R.drawable.btn_unselected);
                isWeChat = false;
            }
        });
        tv_pay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!isWeChat) {
                    aliPay(ordNum, context);
                } else {
                    weChatPay();
                }
                dialog.dismiss();
            }
        });
        pay_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    //TODO
    private void weChatPay() {
        // 商户APP工程中引入微信JAR包，调用API前，需要先向微信注册您的APPID
        final IWXAPI wxapi = WXAPIFactory.createWXAPI(context, CEApp.WECHAT_APP_ID);
        // 将该app注册到微信
        wxapi.registerApp(CEApp.WECHAT_APP_ID);

        String url = "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android";
        HttpAsyncTask task = new HttpAsyncTask() {
            @Override
            public void onStart(String taskId) {

            }

            @Override
            public void onFinish(String taskId, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    if (null != json && !json.has("retcode")) {
                        PayReq req = new PayReq();
                        //req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
                        req.appId = json.getString("appid");
                        req.partnerId = json.getString("partnerid");
                        req.prepayId = json.getString("prepayid");
                        req.nonceStr = json.getString("noncestr");
                        req.timeStamp = json.getString("timestamp");
                        req.packageValue = json.getString("package");
                        req.sign = json.getString("sign");
                        req.extData = "app data"; // optional
                        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                        wxapi.sendReq(req);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        task.setDebug(true);
        task.excute(url, null);
    }


    public void aliPay(String orderNo, final Context context) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("orderNo", orderNo);
        HttpAsyncTask http = new HttpAsyncTask() {
            @Override
            public void onStart(String taskId) {
            }

            @Override
            public void onFinish(String taskId, final String response) {
                final JsonMap data = JsonMap.parseJson(response);
                if (data == null) {
                    Toast.makeText(context, R.string.network_error_tip, Toast.LENGTH_LONG).show();
                    return;
                }

                if (data.getInt("code") == 200) {
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            PayTask alipay = new PayTask((Activity) context);
                            Log.e(this.getClass().getSimpleName(), "aliPaymsg==>" + response);
                            Map<String, String> result = alipay.payV2(data.getString("data"), true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                } else {
                }
            }
        };
        http.setDebug(true);
        http.excute(Url.BaseUrl + "/alipay/rsaSign", params, "POST");
    }

    //支付宝结果回调
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e(this.getClass().getSimpleName(), "resultInfo==>" + resultStatus);
                    Log.e(this.getClass().getSimpleName(), "resultStatus==>" + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
                        payListener.onPaySuccess(resultStatus);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                        payListener.onPayFail();
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    public interface PaySuccessListener {
        void onPaySuccess(String resultStatus);

        void onPayFail();
    }
}
